package com.lanchetech.user.service.impl;

import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanchetech.bean.dto.*;
import com.lanchetech.bean.request.*;
import com.lanchetech.bean.response.*;
import com.lanchetech.bean.util.PageHelpUtil;
import com.lanchetech.bean.util.media.RtcTokenBuilder;
import com.lanchetech.bean.vo.RoomDetailVO;
import com.lanchetech.bean.vo.RoomSpuVO;
import com.lanchetech.bean.vo.RoomStatisticsVO;
import com.lanchetech.bean.vo.RoomVO;
import com.lanchetech.common.enums.DeletedEnum;
import com.lanchetech.common.enums.ResultCode;
import com.lanchetech.common.enums.RoomStatusEnum;
import com.lanchetech.common.enums.ToggleEnum;
import com.lanchetech.dao.*;
import com.lanchetech.entity.*;
import com.lanchetech.service.AgoraService;
import com.lanchetech.service.DaoService;
import com.lanchetech.service.QuartzService;
import com.lanchetech.user.service.CommonService;
import com.lanchetech.user.service.RoomService;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class RoomServiceImpl implements RoomService {

    @Autowired
    RoomMapper roomMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    RoomSpuMapper roomSpuMapper;

    @Autowired
    DaoService daoService;

    @Autowired
    AnchorAttentionMapper anchorAttentionMapper;

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    AnchorLikeMapper anchorLikeMapper;

    @Autowired
    CommonService commonService;

    @Autowired
    AgoraService agoraService;

    @Autowired
    RoomVideoMapper roomVideoMapper;

    @Autowired
    RoomMessageMapper roomMessageMapper;

    @Autowired
    QuartzService quartzService;

    @Autowired
    SpuMapper spuMapper;

    @Autowired
    MsgUserMapper msgUserMapper;

    @Value("${oss.bucket}")
    String bucket;

    @Value("${oss.bucketName}")
    String bucketName;

    @Value("${oss.accessKeyId}")
    String accessKey;

    @Value("${oss.accessKeySecret}")
    String secretKey;

    @Value("${oss.http}")
    String http;

    String appid = "8cc3e6be3564492d8cc8d84d11597eed";

    String signKey = "dd409d41e49048a8807066a5c7a79df0";

    @Override
    public ResultData<RoomDetailVO> getRoomDetail(User user, Long id) {
        RoomDetailVO vo = new RoomDetailVO();
        Room room = roomMapper.selectByPrimaryKey(id);
        vo.setRoom(room);

        User anchor = userMapper.selectByPrimaryKey(room.getAnchorUserId());
        vo.setAvatar(anchor.getAvatar());

        if (user != null) {
            vo.setIsAttention(anchorAttentionMapper.findOneByUserIdAndAnchorUserId(user.getId(), vo.getRoom().getAnchorUserId()) != null);
        } else {
            vo.setIsAttention(false);
        }
        List<RoomMessage> commentList = roomMessageMapper.findLately10Comment(room.getAnchorUserId(), id);
        vo.setCommentList(commentList);
        RoomMessage roomMessage = roomMessageMapper.findSpuMessage(room.getAnchorUserId(), id);
        vo.setRoomSpuMessage(roomMessage);
        RoomSpu onlineSpu = roomSpuMapper.findOneByRoomIdAndStatus(id, ToggleEnum.ON.getStatus());
        if (onlineSpu != null) {
            vo.setSpu(spuMapper.selectByPrimaryKey(onlineSpu.getSpuId()));
        }
        vo.setMsgUserId(msgUserMapper.findOneByRelateId(room.getAnchorUserId()).getId());
        return new ResultData<>(vo);
    }

    @Override
    public ResultData<Long> editRoom(Room room) {
        ResultData<Long> resultData = new ResultData<>();
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (room.getId() == null) {
            Long assistantUserId;
            Date startTime = room.getStartTime();
            Date endTime = room.getEndTime();
            Calendar mincalendar = Calendar.getInstance();
            Calendar maxcalendar = Calendar.getInstance();
            mincalendar.setTime(new Date());
            maxcalendar.setTime(new Date());
            Calendar startCalendar = Calendar.getInstance();
            startCalendar.setTime(startTime);
            mincalendar.add(Calendar.MINUTE, 10);
            maxcalendar.add(Calendar.MONTH, 6);

            long minutes = ChronoUnit.MINUTES.between(Instant.ofEpochMilli(startTime.getTime()), Instant.ofEpochMilli(endTime.getTime()));
            if (startCalendar.before(mincalendar) || startCalendar.after(maxcalendar)) {
                resultData.setResultCode(ResultCode.START_TIME_ERROR);
                return resultData;
            }
            if (minutes < 30 || minutes / 60 > 24) {
                resultData.setResultCode(ResultCode.LIVE_TIME_ERROR);
                return resultData;
            }

            if (room.getAssistantUserId() != null) {
                User assistantUser = userMapper.findOneByUsername(String.valueOf(room.getAssistantUserId()));
                if (assistantUser == null) {
                    resultData.setResultCode(ResultCode.ASSISTANT_NOT_EXIST);
                    return resultData;
                }
                assistantUserId = assistantUser.getId();
            } else {
                assistantUserId = user.getId();
            }


            room.setAnchorUserId(user.getId());
            room.setGoods(0);
            room.setViews(0);
            room.setType(ToggleEnum.OFF.getStatus());
            room.setStatus(RoomStatusEnum.CLOSE.getStatus());
            room.setDeleted(DeletedEnum.DEFAULT.getStatus());
            //todo 租户ID暂时为0
            room.setTenantId(0L);
            room.setCreatedAt(new Date());
            room.setUpdatedAt(new Date());
            room.setAssistantUserId(assistantUserId);
            room.setOfficial(room.getOfficial() != null ? room.getOfficial() : 0);
            room.setSorts(0);

            UserInfo userInfo = userInfoMapper.findOneByUserId(user.getId());
            room.setProvince(userInfo.getProvinceCode());
            room.setCity(userInfo.getCityCode());
            room.setArea(userInfo.getAreaCode());
            roomMapper.insert(room);

            resultData.setValue(room.getId());
            //创建直播间开启订阅
            quartzService.createRoomJob(room);
        } else {
            Room selectRoom = roomMapper.selectByPrimaryKey(room.getId());
            if (RoomStatusEnum.BAN.getStatus().equals(selectRoom.getStatus())) {
                resultData.setResultCode(ResultCode.ROOM_BAN);
                return resultData;
            }
            if (selectRoom.getAnchorUserId().equals(user.getId())) {
                if (RoomStatusEnum.OPEN.getStatus().equals(selectRoom.getStatus()) && ToggleEnum.OFF.getStatus().equals(selectRoom.getCloseComment())) {
                    if (ToggleEnum.ON.getStatus().equals(room.getCloseComment())) {
                        resultData.setResultCode(ResultCode.OPEN_COMMENT_FAIL);
                        return resultData;
                    }
                }
                roomMapper.updateByPrimaryKeySelective(room);

                //如果修改了开始时间
                if (room.getStartTime() != null) {
                    Calendar startTime = Calendar.getInstance();
                    startTime.setTime(room.getStartTime());
                    startTime.add(Calendar.MINUTE, -5);
                    String startCron = String.format("%d %d %d %d %d ? %d",
                            startTime.get(Calendar.SECOND),
                            startTime.get(Calendar.MINUTE),
                            startTime.get(Calendar.HOUR_OF_DAY),
                            startTime.get(Calendar.DAY_OF_MONTH),
                            startTime.get(Calendar.MONTH) + 1,
                            startTime.get(Calendar.YEAR));
                    quartzService.modifyJobTime("ROOM_TRIGGER" + room.getId().toString(), "ROOM_START_NOTIFY", startCron);
                }
            }
        }
        return resultData;
    }

    @Override
    public BaseResp closeRoom(Long id) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Room room = roomMapper.selectByPrimaryKey(id);
        if (room.getAnchorUserId().equals(user.getId())) {
            roomMapper.updateStatusById(RoomStatusEnum.CLOSE.getStatus(), id);
        }
        return new BaseResp();
    }

    @Override
    public ResultData<BasePageResp<RoomVO>> getRoomPage(User user, RoomReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        req.setStatus(RoomStatusEnum.OPEN.getStatus());
        List<Room> list = roomMapper.findAllPage(req);
        List<RoomVO> voList = new ArrayList<>();

        if (!CollectionUtils.isEmpty(list)) {
            Map<Long, User> userMap = daoService.getUserMap(list.stream().map(Room::getAnchorUserId).collect(Collectors.toList()));
            Map<Long, AnchorLike> anchorLikeMap = new HashMap<>();
            Map<Long, AnchorAttention> anchorAttentionMap = new HashMap<>();
            if (user != null) {
                //直播间是否点赞
                List<AnchorLike> anchorLikes = anchorLikeMapper.findAllByUserId(user.getId());
                if (!CollectionUtils.isEmpty(anchorLikes)) {
                    anchorLikes.stream().forEach(item -> {
                        anchorLikeMap.put(item.getRoomId(), item);
                    });
                }

                //主播是否关注
                List<AnchorAttention> anchorAttentions = anchorAttentionMapper.findAllByUserId(user.getId());
                if (!CollectionUtils.isEmpty(anchorLikes)) {
                    anchorAttentions.stream().forEach(item -> {
                        anchorAttentionMap.put(item.getAnchorUserId(), item);
                    });
                }
            }


            list.stream().forEach(item -> {
                RoomVO vo = new RoomVO();
                BeanUtils.copyProperties(item, vo);
                vo.setUserAvatar(userMap.get(item.getAnchorUserId()).getAvatar());
                vo.setUserNickname(userMap.get(item.getAnchorUserId()).getNickname());
                vo.setIsLike(anchorLikeMap.containsKey(item.getId()));
                vo.setIsAttention(anchorAttentionMap.containsKey(item.getAnchorUserId()));
                voList.add(vo);
            });
        }

        return PageHelpUtil.buildPage(voList, page);
    }

    @Override
    public ResultData<BasePageResp<Room>> getMyRoomPage(RoomReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        req.setAnchorUserId(user.getId());
        List<Room> list = roomMapper.findAllPage(req);
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public BaseResp deleteRoom(Long id) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Room room = roomMapper.selectByPrimaryKey(id);
        if (room.getAnchorUserId().equals(user.getId())) {
            roomMapper.updateDeletedById(DeletedEnum.DELETED.getStatus(), id);
        }
        return new BaseResp();
    }

    @Override
    public BaseResp addRoomSpu(Long roomId, Long spuId) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Room selectRoom = roomMapper.selectByPrimaryKey(roomId);
        if (selectRoom != null) {
            if (user.getId().equals(selectRoom.getAssistantUserId()) || user.getId().equals(selectRoom.getAnchorUserId())) {
                List<RoomSpu> roomSpuList = roomSpuMapper.findAllByRoomId(roomId);
                int maxSorts = 0;
                if (!CollectionUtils.isEmpty(roomSpuList)) {
                    maxSorts = roomSpuMapper.maxSorts(roomId);
                }
                roomSpuMapper.insert(RoomSpu.builder()
                        .roomId(roomId)
                        .userId(user.getId())
                        .spuId(spuId)
                        .sorts(maxSorts + 1)
                        .status(ToggleEnum.OFF.getStatus())
                        .createdAt(new Date())
                        .updatedAt(new Date())
                        .build());
            } else {
                return new BaseResp(ResultCode.OPERATION_ROOM_FAIL);
            }
        }
        return new BaseResp();
    }

    @Override
    public BaseResp deleteRoomSpu(Long roomSpuId) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        RoomSpu roomSpu = roomSpuMapper.selectByPrimaryKey(roomSpuId);
        Room selectRoom = roomMapper.selectByPrimaryKey(roomSpu.getRoomId());
        if (user.getId().equals(selectRoom.getAssistantUserId()) || user.getId().equals(selectRoom.getAnchorUserId())) {
            roomSpuMapper.deleteByPrimaryKey(roomSpuId);
            List<RoomSpu> list = roomSpuMapper.findAllByRoomId(selectRoom.getId());
            for (int i = 1; i <= list.size(); i++) {
                list.get(i - 1).setSorts(i);
            }
            roomSpuMapper.updateSotrsBatch(list);
        } else {
            return new BaseResp(ResultCode.OPERATION_ROOM_FAIL);
        }
        return new BaseResp();
    }

    @Override
    public BaseResp editRoomSpuSorts(RoomSpuReq req) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Room selectRoom = roomMapper.selectByPrimaryKey(req.getRoomId());
        if (user.getId().equals(selectRoom.getAssistantUserId()) || user.getId().equals(selectRoom.getAnchorUserId())) {
            roomSpuMapper.updateBatch(req.getRoomSpuList());
        } else {
            return new BaseResp(ResultCode.OPERATION_ROOM_FAIL);
        }
        return new BaseResp();
    }

    @Override
    public BaseResp editRoomSpuStatus(Long roomSpuId, Byte status) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        RoomSpu roomSpu = roomSpuMapper.selectByPrimaryKey(roomSpuId);
        Room selectRoom = roomMapper.selectByPrimaryKey(roomSpu.getRoomId());
        if (user.getId().equals(selectRoom.getAssistantUserId()) || user.getId().equals(selectRoom.getAnchorUserId())) {
            //只存在一件上架商品
            if (RoomStatusEnum.OPEN.getStatus().equals(status)) {
                roomSpuMapper.updateStatusByRoomId(RoomStatusEnum.CLOSE.getStatus(), selectRoom.getId());
            }
            roomSpuMapper.updateStatusById(status, roomSpuId);
        } else {
            return new BaseResp(ResultCode.OPERATION_ROOM_FAIL);
        }
        return new BaseResp();
    }

    @Override
    public ResultData<List<RoomSpuVO>> getRoomSpuList(Long roomId) {
        List<RoomSpuVO> voList = new ArrayList<>();
        List<RoomSpu> roomSpuList = roomSpuMapper.findAllByRoomId(roomId);
        if (!CollectionUtils.isEmpty(roomSpuList)) {
            Map<Long, Spu> spuMap = daoService.getSpuMap(roomSpuList.stream().map(RoomSpu::getSpuId).collect(Collectors.toList()));
            roomSpuList.stream().forEach(item -> {
                RoomSpuVO vo = new RoomSpuVO();
                BeanUtils.copyProperties(item, vo);
                vo.setSpu(spuMap.get(item.getSpuId()));
                voList.add(vo);
            });
        }
        return new ResultData<>(voList);
    }

    @Override
    public BaseResp attentionAnchor(Long anchorUserId) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long userId = user.getId();
        if (!user.getId().equals(anchorUserId)) {
            UserInfo anchorInfor = userInfoMapper.findOneByUserId(anchorUserId);
            UserInfo userInfo = userInfoMapper.findOneByUserId(userId);
            AnchorAttention anchorAttention = anchorAttentionMapper.findOneByUserIdAndAnchorUserId(userId, anchorUserId);
            if (anchorAttention == null) {
                anchorAttentionMapper.insert(AnchorAttention.builder()
                        .userId(userId)
                        .anchorUserId(anchorUserId)
                        .createdAt(new Date())
                        .build());
                anchorInfor.setFansCount(anchorInfor.getFansCount() + 1);
                userInfoMapper.updateByPrimaryKey(anchorInfor);

                userInfo.setAttentionCount(userInfo.getAttentionCount() + 1);
                userInfoMapper.updateByPrimaryKey(userInfo);
            } else {
                anchorAttentionMapper.deleteByPrimaryKey(anchorAttention.getId());
                anchorInfor.setFansCount(anchorInfor.getFansCount() - 1);
                userInfoMapper.updateByPrimaryKey(anchorInfor);

                userInfo.setAttentionCount(userInfo.getAttentionCount() - 1);
                userInfoMapper.updateByPrimaryKey(userInfo);
            }
        }
        return new BaseResp();
    }

    @Override
    public BaseResp likeAnchor(Long roomId) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long userId = user.getId();
        Room room = roomMapper.selectByPrimaryKey(roomId);
        if (room != null && !user.getId().equals(room.getAnchorUserId())) {
            AnchorLike anchorLike = anchorLikeMapper.findOneByUserIdAndRoomId(userId, roomId);
            if (anchorLike == null) {
                anchorLikeMapper.insert(AnchorLike.builder()
                        .userId(userId)
                        .anchorUserId(room.getAnchorUserId())
                        .roomId(roomId)
                        .createdAt(new Date())
                        .build());
                room.setGoods(room.getGoods() + 1);
                roomMapper.updateByPrimaryKey(room);
            } else {
                anchorLikeMapper.deleteByPrimaryKey(anchorLike.getId());
                room.setGoods(room.getGoods() - 1);
                roomMapper.updateByPrimaryKey(room);
            }
        }
        return new BaseResp();
    }

    @Override
    public BaseResp sendRoomMessage(WsSendToUserReq req) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // TODO 在这里对消息进入持久化储存
        roomMessageMapper.insert(RoomMessage.builder()
                .userId(user.getId())
                .anchorUserId(req.getAnchorUserId())
                .type(req.getMessageType())
                .content(req.getMessage())
                .createdAt(new Date())
                .roomId(req.getRoomId())
                .build());
        return commonService.postToIm(req);
    }

    @Override
    public BaseResp startRecord(String cname, Long roomId) {
        RoomVideo roomVideo = roomVideoMapper.findOneByRoomId(roomId);

        //获取范围 1 到 4294967295 作为录制uid 且不与频道内uid重复


        //获取频道内所有uid
        ChannelUserDTO channelUser = agoraService.getChannelUser(appid, cname);
        List<String> anchorIds = channelUser.getBroadcasters();
        List<String> userIds = channelUser.getAudience();


        //获取录制资源
        RecordingResourcesReq recordingResourcesReq = new RecordingResourcesReq();
        ClientRequest clientRequest = new ClientRequest();
        clientRequest.setRegion("CN");
        clientRequest.setResourceExpiredHour(24);
        recordingResourcesReq.setCname(cname);
        recordingResourcesReq.setUid("527841");
        recordingResourcesReq.setClientRequest(clientRequest);
        String resourcesId = agoraService.getRecordingResources(recordingResourcesReq);

        RtcTokenBuilder rtcTokenBuilder = new RtcTokenBuilder();

        //开始录制
        StartRecordReq startRecordReq = new StartRecordReq();
        StartRecordDTO startRecordDTO = new StartRecordDTO();
        ClientRequestDTO startClientRequest = new ClientRequestDTO();
        startClientRequest.setToken(rtcTokenBuilder.buildTokenWithUid(appid, signKey, cname, 0, RtcTokenBuilder.Role.Role_Publisher, (int) (DateTime.now().getMillis() / 1000) + 60 * 60 * 12));
        RecordingConfigDTO recordingConfigDTO = new RecordingConfigDTO();
        recordingConfigDTO.setVideoStreamType(0);
        recordingConfigDTO.setMaxIdleTime(30);
        recordingConfigDTO.setStreamTypes(2);
        recordingConfigDTO.setChannelType(1);
        recordingConfigDTO.setSubscribeUidGroup(0);
        recordingConfigDTO.setAudioProfile(1);
        TranscodingConfigDTO transcodingConfigDTO = new TranscodingConfigDTO();
        transcodingConfigDTO.setHeight(640);
        transcodingConfigDTO.setWidth(360);
        transcodingConfigDTO.setBitrate(500);
        transcodingConfigDTO.setFps(15);
        transcodingConfigDTO.setMixedVideoLayout(1);
        transcodingConfigDTO.setBackgroundColor("#FF0000");
        recordingConfigDTO.setTranscodingConfig(transcodingConfigDTO);
        recordingConfigDTO.setSubscribeVideoUids(anchorIds);
        recordingConfigDTO.setSubscribeAudioUids(anchorIds);
        startClientRequest.setRecordingConfig(recordingConfigDTO);
        StorageConfigDTO storageConfigDTO = new StorageConfigDTO();
        storageConfigDTO.setVendor(2);
        storageConfigDTO.setRegion(0);
        storageConfigDTO.setAccessKey(accessKey);
        storageConfigDTO.setSecretKey(secretKey);
        storageConfigDTO.setBucket(bucketName);
        List<String> fileNamePrefix = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());
        fileNamePrefix.add("video");
        fileNamePrefix.add(date);
        storageConfigDTO.setFileNamePrefix(fileNamePrefix);
        startClientRequest.setStorageConfig(storageConfigDTO);
        RecordingFileConfigDTO recordingFileConfigDTO = new RecordingFileConfigDTO();
        List<String> avFileType = new ArrayList<>();
        avFileType.add("hls");
        avFileType.add("mp4");
        recordingFileConfigDTO.setAvFileType(avFileType);
        startClientRequest.setRecordingFileConfig(recordingFileConfigDTO);
        startRecordDTO.setCname(cname);
        startRecordDTO.setUid("527841");
        startRecordDTO.setClientRequest(startClientRequest);
        startRecordReq.setMode("mix");
        startRecordReq.setResourceid(resourcesId);
        startRecordReq.setStartRecordDTO(startRecordDTO);
        StartRecordResp resp = agoraService.startRecord(startRecordReq);

        if (roomVideo == null) {

            roomVideoMapper.insert(RoomVideo.builder()
                    .roomId(roomId)
                    .cname(cname)
                    .sid(resp.getSid())
                    .resourceId(resp.getResourceId())
                    .createdAt(new Date())
                    .videoUrl(http + bucket + "video/" + date)
                    .uid("527841")
                    .build());
        } else {
            roomVideo.setSid(resp.getSid());
            roomVideo.setResourceId(resp.getResourceId());
            roomVideo.setVideoUrl(http + bucket + "video/" + date);
            roomVideoMapper.updateByPrimaryKey(roomVideo);
        }

        return new BaseResp();
    }

    @Override
    public BaseResp stopRecord(String cname, Long roomId) {
        RoomVideo roomVideo = roomVideoMapper.findOneByRoomId(roomId);
        StopRecordReq stopRecordReq = new StopRecordReq();
        stopRecordReq.setMode("mix");
        stopRecordReq.setSid(roomVideo.getSid());
        stopRecordReq.setResourceid(roomVideo.getResourceId());
        StopRecordDTO stopRecordDTO = new StopRecordDTO();
        stopRecordDTO.setCname(cname);
        stopRecordDTO.setUid(roomVideo.getUid());
        ClientStopRequestDTO clientStopRequestDTO = new ClientStopRequestDTO();
        clientStopRequestDTO.setAsync_stop(false);
        stopRecordDTO.setClientRequest(clientStopRequestDTO);
        stopRecordReq.setStopRecordDTO(stopRecordDTO);
        StopRecordResp stopRecordResp = agoraService.stopRecord(stopRecordReq);

        List<String> files = new ArrayList<>();
        stopRecordResp.getServerResponse().getFileList().stream().forEach(item -> {
            if (item.getFileName().contains(".mp4")) {
                files.add(http + bucket + item.getFileName());
            }
        });
        roomVideoMapper.updateVideoUrlByRoomId(JSON.toJSONString(files), roomId);

        return new BaseResp();
    }

    @Override
    public ResultData<QueryRecordResp> queryRecord(Long roomId) {
        RoomVideo roomVideo = roomVideoMapper.findOneByRoomId(roomId);
        QueryRecordReq queryRecordReq = new QueryRecordReq();
        queryRecordReq.setMode("mix");
        queryRecordReq.setSid(roomVideo.getSid());
        queryRecordReq.setResourceid(roomVideo.getResourceId());
        QueryRecordResp queryRecordResp = agoraService.queryRecord(queryRecordReq);
        return new ResultData<>(queryRecordResp);
    }

    @Override
    public String getLiveToken(User user, Long roomId, int role) {

        Long userId = user == null ? 0L : user.getId();

        RtcTokenBuilder token = new RtcTokenBuilder();
        int timestamp = (int) (System.currentTimeMillis() / 1000 + 60 * 60 * 24);
        String result = "";
        if (role == 1) {
            result = token.buildTokenWithUid(appid, signKey, roomId.toString(), userId.intValue(), RtcTokenBuilder.Role.Role_Publisher, timestamp);
        }
        if (role == 2) {
            result = token.buildTokenWithUid(appid, signKey, roomId.toString(), userId.intValue(), RtcTokenBuilder.Role.Role_Subscriber, timestamp);
        }
        return result;
    }

    @Override
    public ResultData<List<String>> getRoomPlayback(Long roomId) {
        RoomVideo roomVideo = roomVideoMapper.findOneByRoomId(roomId);
        List<String> videos = new ArrayList<>();
        if (roomVideo != null) {
            if (roomVideo.getVideoUrl().contains("[")) {
                videos = JSON.parseArray(roomVideo.getVideoUrl(), String.class);
            }
        }
        return new ResultData<>(videos);
    }

    @Override
    public ResultData<List<RoomStatisticsVO>> getRoomStatistics(Long roomId) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Room room = roomMapper.selectByPrimaryKey(roomId);
        //直播或者助理能查看数据
        if (room.getAnchorUserId().equals(user.getId()) || user.getId().equals(room.getAssistantUserId())) {
            return new ResultData<>(roomMessageMapper.getRoomStatistics(roomId));
        } else {
            return new ResultData<>(null);
        }
    }
}
